<script>
	import ForceGraph3D from '3d-force-graph';
	import { onMount } from 'svelte';
	import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';
	let width, height;

	const bloomPass = new UnrealBloomPass();
	bloomPass.strength = 3;
	bloomPass.radius = 1;
	bloomPass.threshold = 0.1;
	// bloomPass.backgroundColor = rgba(0, 0, 0, 0);
	let source = '../graph/miserables.json';
	const distance = 1000;
	const NODES = 200;
	const GROUPS = 12;
	const gData = {
		nodes: [...Array(NODES).keys()].map((i) => ({
			id: i,
			group: Math.ceil(Math.random() * GROUPS)
		})),
		links: [...Array(NODES).keys()]
			.filter((id) => id)
			.map((id) => ({
				source: id,
				target: Math.round(Math.random() * (id - 1))
			}))
	};
	let demo;
	onMount(() => {
		const graphdemo = document.getElementById('3d-graph');
		width = innerWidth;

		console.log(width, height);
		demo = ForceGraph3D({ controlType: 'orbit' });

		// demo(graphdemo); .backgroundColor('rgba(147,197,253,0.1)');
		demo(graphdemo)
			.width(width - width / 5 - 50)
			.height(height)
			.cooldownTicks(100)
			.cameraPosition({ z: distance })
			.onNodeDragEnd((node) => {
				node.fx = node.x;
				node.fy = node.y;
				node.fz = node.z;
			})
			.backgroundColor('rgba(0,0,0,0)')

			.showNavInfo(false)
			.graphData(gData)
			.nodeRelSize(5)
			.nodeAutoColorBy('group')
			.linkAutoColorBy((d) => gData.nodes[d.source].group)
			.linkOpacity(0.8)
			.linkDirectionalParticles('value')
			.linkDirectionalParticleSpeed((d) => d.value * 0.001)
			.linkDirectionalArrowLength(8)
			.linkDirectionalArrowRelPos(1)
			.linkCurvature(0.25)
			.nodeOpacity(0.9)
			.postProcessingComposer()
			.addPass(bloomPass);

		// fit to canvas when engine stops
		// demo.onEngineStop(() => demo.zoomToFit(800));
		let angle = 0;
		setInterval(() => {
			demo.cameraPosition({
				x: distance * Math.sin(angle),
				z: distance * Math.cos(angle)
			});
			angle += Math.PI / 600;
		}, 10);
	});
	function resetwindows() {
		({ width } = demo);
	}
</script>

<svelte:window on:resize={resetwindows} />
<div id="3d-graph" />
